<template>

  <div class="edit">
    <!-- 编辑页面 -->
    <el-tabs v-model="activeName" type="card" >
      <el-tab-pane label="基础信息" name="first">
         <div class="edits">
    <el-form ref="form" :model="form" label-width="80px">
      <!-- 所属分类 -->
      <el-form-item label="所属分类">
        <el-select v-model="form.category" placeholder="请选择所属分类"  >
          <el-option :value="item.id"  :label="item.name" v-for="item in fenlei" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- 商品名称 -->
      <el-form-item label="商品名称">
        <el-input v-model="form.goodsname" width="80px"></el-input>
      </el-form-item>
      <!-- 所属品牌 -->
      <el-form-item label="所属品牌">
        <el-select v-model="form.brand" placeholder="请选择所属品牌">
          <el-option  :value="item.id" :label="item.name"  v-for=" item in brandlist" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- 商品简介 -->
      <el-form-item label="商品简介" prop="desc">
        <el-input type="textarea" v-model="form.desc"></el-input>
      </el-form-item>
      <!-- 商品图片 -->
      <el-form-item label="商品图片">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :headers="headers"
          name="good_pic"
          :http-request="uploadGoodPicFn"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" width="100%"/>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <span>推荐图片尺寸：750*420</span>
      </el-form-item>

      <!-- 轮播图图片 -->

      <el-form-item label="轮播图图片">
        <el-upload
          action="http://kumanxuan1.f3322.net:8360/admin/upload/goodNewPic"
          list-type="picture-card"
          :before-upload="beforeAvatarUpload"
          :on-remove="removeFn"
          :file-list = "fileList"
          :headers="headers"
          name="good_pic"
          :on-success="uploadSuccessFn"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        
      </el-form-item>

      <el-form-item label="商品单位">
        <el-input v-model="form.goodsunit" width="80px"></el-input>
      </el-form-item>

      <el-form-item label="商品库存">
        <el-input v-model="form.repertory" width="80px"></el-input>
      </el-form-item>

      <el-form-item label="商品价格">
        <el-input v-model="form.price" width="80px"></el-input>
      </el-form-item>

      <el-form-item label="推荐类型">
      
          <el-checkbox
          label="新品"
          name="new"
          true-label=1
          false-label=0
          v-model="is_new"
           >新品</el-checkbox>

          <el-checkbox 
          label="人气"
          name="hot"
          true-label='1'
          false-label='0'
          v-model ="is_hot"
          >人气</el-checkbox>
      
      </el-form-item>

      <el-form-item label="上架">
        <el-switch
          v-model="is_delete"
          active-value="0" 
          inactive-value="1"
          active-color="#409eff"
          inactive-color="#dcdfe6"
        >

        </el-switch>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="form.sort" width="80px"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="preserveFn">确认保存</el-button>
        <el-button @click="closeFn">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
      </el-tab-pane>



           <el-tab-pane label="商品属性" name="second">
        <GoodAttribute :attribute="attribute" />
      </el-tab-pane>
      <el-tab-pane label="商品详情" name="third">
        <GoodDetails />
      </el-tab-pane>
    </el-tabs>




  </div>
</template>

<script>

import GoodAttribute from './GoodAttribute.vue'
import GoodDetails from './GoodDetails.vue'
const {getGoodInfo,getCategoryLists,getBrandLists,editGoodInfo,uploadGoodPic} = require("../../request/httpApi")
export default {
  data() {


    return {
      headers:{
        'X-Nideshop-Token':localStorage.getItem('token')
      },
      form: { 
         //显示的name
        name:'',
        //商品名称
        goodsname:'',
        //商品单位
        goodsunit:'',
        //商品 库存
        repertory:'',
        //排序
        sort:'',
        //价格
        price:'',
        //品牌
        brand: "",
        type: [],
        desc: "",
        //分类的id
        category:''
      },
      //上传图片的初始值
      imageUrl: "",
      //开关按钮
      is_delete:'',
      //所属分类
      fenlei:[],
      //所属品牌
      brandlist:[],
      //人气和新品
      is_hot:'',
      is_new:'',
      data:{},
      //轮播图渲染数组
      fileList:[],
      //轮播图的添加数组
      fileListArr:[],
      //接口id
      myid:'',

      activeName: "first",
      attribute:[]

    };

  },
  components:{
      GoodAttribute,GoodDetails
  },

  created(){


     //判断页面有没有id 如果有就是编辑页面 id就等于路径上的
      //如果没有直接使用默认值
      // if(this.$route.path.includes("editgood")){
      //     this.myid = this.$route.params.gid 
      // }

    //加载之后的页面的数据请求
    getGoodInfo({
      id:this.$route.params.gid
    }).then( res => {
      if(res.errno ===0){

         console.log(res.data);
         this.form.category = res.data.category_id
         this.form.brand = res.data.brand_id
         this.form.goodsname = res.data.name,
         this.form.goodsunit = res.data.goods_unit
         this.form.repertory =  res.data.goods_number
         this.form.sort = res.data.sort_order
         this.form.price = res.data.retail_price
         this.is_delete = res.data.is_delete.toString()
         this.form.desc = res.data.goods_brief
         this.is_hot = res.data.is_hot.toString()
         this.is_new = res.data.is_new.toString()
         this.data = res.data
         this.imageUrl = res.data.primary_pic_url
         this.attribute = res.data.attribute

       
        //将轮播图数组拷贝一份 作为添加的数组项
        this.fileList  = JSON.parse(JSON.stringify(res.data.gallery))


        //渲染数组的格式需要{url:xxx} 所以map得到的数组
       this.fileList.map(  item => {
          item.url = item.img_url
          this.fileListArr.push(item.img_url)

        })
        // console.log(this.fileList);
        // console.log(this.fileListArr);
  
      }


    }),
    //品牌分类的接口
    getBrandLists().then( res => {
      if(res.errno === 0) {
        this.brandlist = res.data.data
      }
    })

     //查询分类接口 
    getCategoryLists().then(res => {
      if(res.errno === 0) {
        this.fenlei = res.data
      }
    })

    //商品属性的数据接口 
  //  getAttrInfo({ id:this.$route.params.gid}).then( res => {
  //     console.log(res);
  //     if(res.errno===0) {
  //       this.attribute = res.data
  //     }
  //   })
  },

  methods: {

    //l轮播图 图片上传成功的钩子
    uploadSuccessFn(file){
      // console.log(file.data.fileUrl);
      //拿到上传图片的路径,把它放入轮播图的添加数组
      this.fileListArr.push(file.data.fileUrl)
      // console.log(this.fileListArr);
    },
    
    //图片上传封装
    uploadGoodPicFn(data){
      // console.log(file);
      let formdata = new FormData()
      formdata.append('good_pic',data.file)
      uploadGoodPic(formdata).then( res => {
        // console.log(res);
        //把从服务器获取的图片地址保存到data里 
        if(res.errno ===0){
          //替换当前图片
          this.imageUrl = res.data.fileUrl
        }
      })
    },

    //beforeAvatarUpload 上传图片 的大小限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt50K = file.size / 1024 / 1024 / 1024 < 50;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt50K) {
        this.$message.error("上传头像图片大小不能超过 50K!");
      }
      return isJPG && isLt50K;
    },



    //轮播图删除事件
    removeFn(file){
      // console.log(this.fileListArr);
      console.log(file.url);
      //获取将要删除的图片的路径
  
      const filePath  = file.url
      //从数组中,找到需要删除的图片的对应索引值
      console.log(this.fileListArr);
       const i = this.fileListArr.findIndex( item => item === filePath )
       console.log(i);
      // //调用splice方法
      this.fileListArr.splice(i,1)
      // console.log(this.fileListArr);

    },


    // 点击保存 发送请求   
    //在create中判断,如果有id就是修改页面,没有id则是添加页面
    preserveFn(){
      
      //非空校验 
      if(this.form.goodsname ==='' || this.form.desc=== '' ){
        this.$message.error("商品名称和简介必填")
        return
      }

      //确认之后 需要传递的参数
      editGoodInfo({
        id:this.$route.params.gid,
        category_id:Number(this.form.category),   //所属分类
        name:this.form.goodsname,  //商品名称
        brand_id:this.form.brand,  //所属品牌
        goods_number:this.form.repertory, //商品数量
        goods_brief:this.form.desc,   //简介
        goods_unit:this.form.goodsunit,  //商品库存
        retail_price:Number(this.form.price), //商品价格
        sort_order:Number( this.form.sort),  //排序
        is_hot:  Number(this.is_hot)  ,  //人气
        is_new:Number(this.is_new),//新品
        is_delete:Number(this.is_delete),   //上架
        primary_pic_url:this.imageUrl,  //头像图片
        list_pic_url:this.imageUrl,
        gallerys:this.fileListArr ,   //轮播图数组  
        attribute:[] //商品详情

      }).then( res =>{

        if(res.errno === 0){
          //判断url是否有id 有id提示修改成功  没有id 提示添加成功  并跳转到good页面
          this.$route.params.gid?this.$message.success("修改成功"):this.$message.success("添加成功")
          this.$router.push("/good")
        }
      })
    },
    // ///点击取消 返回之前页面
     closeFn(){
        this.router.go(-1)
      }

  },
  
};
</script>

<style lang="less" >
.edit {
  background-color: #fff;
}


.edits {
  .el-tabs__header {
    margin: 0;
  
  }
  .el-tabs--card>.el-tabs__header{
      background-color: #f5f7fa;
  }

  .el-form {
  padding: 20px 0 20px 40px;

  .el-form-item {
    .el-input__inner,
    .el-textarea,
    .el-input{
      width: 225px;
    }

    .el-form-item__label {
    padding: 0px 10px 0 0;
    }
     .el-form-item__content>span{
        color: #ccc;
      }


    /* 头像的样式 */
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 187px;
        height: 105px;
        /* // 推荐图片尺寸：750*420 */
        line-height: 105px;
        text-align: center;
        border: 1px solid #d9d9d9;
      }
      .avatar {
       width: 187px;
        height: 105px;
        display: block;
      }
  }
  }
}
</style>